<template>
  <!-- 接入应用及模块信息编辑 -->
  <basic-container class="apps">
    <div v-if="id" class="flexbox">
      <TokenImg :img-url="imgBaseUrl + Form.icon" />
      <!-- <img :src="imgBaseUrl + Form.icon" alt=""> -->
      <div class="flex">
        <h3>{{ Form.accessName }}</h3>
        <span :class="Number(Form.status) ? 'bg-green' : 'bg-red'">{{ Number(Form.status) ? '启用' : '禁用' }}</span>
      </div>
    </div>
    <h4>接入应用及模块信息</h4>
    <el-form ref="Form" :model="Form" :rules="rules" label-width="100px" class="formClass">
      <div class="formContent">
        <div class="up">
          <div class="left">
            <el-row>
              <el-col :span="12">
                <el-form-item label="所属应用:" prop="appId">
                  <el-select v-model="Form.appId" :disabled="isEdit" clearable @change="selectChange1">
                    <el-option v-for="(item,index) in appList" :key="index" :label="item.appname" :value="item.appid" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属模块:" prop="accessName">
                  <el-input v-model="Form.accessName" class="inputClass" :disabled="isEdit" clearable @change="isNull" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="接入应用集:" prop="appSetId">
                  <el-select v-model="Form.appSetId" :disabled="isEdit" clearable @change="selectChange">
                    <el-option v-for="(item, index) in appSetList" :key="index" :label="item.appname" :value="item.appid" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="业务体系:" prop="businessSystem">
                  <el-select v-model="Form.businessSystem" :disabled="disabled" clearable>
                    <el-option v-for="(item) in BusinessSystemList" :key="item.key" :label="item.value" :value="item.key" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div class="right">
            <el-row>
              <el-col>
                <el-form-item label="应用图标:" prop="icon">
                  <el-upload
                    class="avatar-uploader"
                    :show-file-list="false"
                    action="/api/file/upload"
                    :headers="{'Token':Token, 'SsoToken':SsoToken}"
                    :on-success="success"
                    :before-upload="typeJudge"
                    accept="image/*"
                  >
                    <!-- :auto-upload="false"
                    :on-change="handleUploadChange" -->
                    <div v-if="Form.icon" class="flexbox">
                      <TokenImg :img-url="imgBaseUrl + Form.icon" style="width: 50px;height: 50px;" />
                      <!-- <img :src="imgBaseUrl + Form.icon" alt="" style="width: 50px;height: 50px;"> -->
                      <div class="ml20" style="color: #0368d1;">重新上传图片</div>
                    </div>
                    <div v-else>
                      <i class="el-icon-plus avatar-uploader-icon" />
                    </div>
                    <div slot="tip" class="el-upload__tip">温馨提示：请上传200px*200px的高清图标<br>（支持jpg、bmp、png、svg等格式）</div>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
        <div class="down">
          <el-row>
            <el-col :span="23">
              <el-form-item label="接入描述:" prop="describe" style="margin-bottom: 0;">
                <el-input v-model="Form.describe" type="textarea" />
                <div style="color:red;">接入描述用于简单描述应用或模块功能，将显示在前端，请规范填写！</div>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>
      <h4>接入配置</h4>
      <div class="formContent">
        <el-row>
          <el-col :span="14">
            <el-form-item label="访问地址：" prop="url">
              <el-input v-model="Form.url" />
              <!-- <div style="color:red;">访问地址是iP地址时，需要填写完整。前面需要带有http://或者https://协议</div> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="14">
            <el-form-item label="权限码：" prop="authCode">
              <el-input v-model="Form.authCode" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="14">
            <el-form-item label="不可使用权限码：" prop="noAuthCode">
              <el-input v-model="Form.noAuthCode" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <CropperImgDialog
      ref="cropper"
      title="裁剪图片"
      :visible.sync="visible"
      :cropper-file="{original: originalImg}"
      :confirm="handleCroppedConfirm"
    />
    <div class="btn-group">
      <el-button type="primary" @click="submitForm('Form')">{{ id?'保存':'确定' }}</el-button>
      <el-button @click="cancel">取消</el-button>
    </div>
    <ConfirmDialog ref="dialog" content="确认是否保存?" @confirm="save" @cancel="$refs.dialog.setDialogVisible(false)" />
    <ConfirmDialog1 ref="dialog1" content="保存成功" />
  </basic-container>

</template>

<script>
import ConfirmDialog from '@/components/common/ConfirmDialog'
import CropperImgDialog from '@/components/CropperImgDialog/index.vue'
import ConfirmDialog1 from '@/components/common/ConfirmDialog1'
import { edit, detail, app, appSet, getBusinessSystem } from '@/api/appAndModule/index.js'
import { getToken, getSsoToken } from '@/util/auth' // setTokenConfig
import TokenImg from '@/components/common/TokenImg.vue'
export default {
  name: 'EditAppAndModule',
  components: { ConfirmDialog, ConfirmDialog1, TokenImg, CropperImgDialog },
  data() {
    const urlValidate = (rule, value, callback) => {
      if (value.toLowerCase().indexOf('http') !== 0) {
        callback(new Error('访问地址是iP地址时，需要填写完整。前面需要带有http://或者https://协议'))
      } else {
        callback()
      }
    }
    return {
      visible: false,
      originalImg: '',
      cropped: {},
      Token: '',
      SsoToken: '',
      id: this.$route.query.id ? this.$route.query.id : null,
      Form: {
        'accessName': '',
        'appId': '',
        'appSetId': '',
        'authCode': '',
        'noAuthCode': '', // 不可使用权限码
        'businessSystem': '',
        'describe': '',
        'icon': '',
        'id': null,
        'url': ''
      },
      rules: {
        appId: [
          { required: true, message: '请选择所属应用', trigger: 'change' }
        ],
        icon: [
          { required: true, message: '请上传应用图标', trigger: 'change' }
        ],
        appSetId: [
          { required: true, message: '请选择接入应用集', trigger: 'change' }
        ],
        businessSystem: [
          { required: true, message: '请选择业务体系', trigger: 'change' }
        ],
        url: [
          { required: true, message: '请输入访问地址', trigger: 'blur' },
          { validator: urlValidate, trigger: 'blur' }
        ]
      },
      isEdit: false,
      disabled: false,
      imgUrl: '',
      appList: [],
      appSetList: [],
      BusinessSystemList: [],
      imgBaseUrl: process.env.VUE_APP_BASE_API
    }
  },
  created() {
    this.Token = getToken()
    this.SsoToken = getSsoToken()
    if (this.id) {
      this.getDeatil()
    }
    app().then(res => {
      this.appList = res.data.data
    })
    appSet().then(res => {
      this.appSetList = res.data.data
    })
  },
  methods: {
    getDeatil() {
      const params = { id: this.id }
      detail(params).then((res) => {
        const data = res.data.data
        this.Form = data
        this.isEdit = true
        if (this.Form.accessName) {
          this.disabled = true
        }
        if (data.appSetId) {
          const params = {
            appSetId: data.appSetId
          }
          getBusinessSystem(params).then(res => {
            this.BusinessSystemList = res.data.data
          })
        }
      })
    },
    save() {
      delete this.Form.status
      edit(this.Form).then(() => {
        this.$refs.dialog1.setDialogVisible(true)
        setTimeout(() => {
          this.$refs.dialog1.setDialogVisible(false)
          this.$router.push({ name: '应用及模块接入', params: { isRefresh: true }})
        }, 500)
      })
    },
    submitForm(val) {
      this.$refs[val].validate((valid) => {
        if (valid) {
          this.$refs.dialog.setDialogVisible(true)
        } else {
          return false
        }
      })
    },
    cancel() {
      this.$router.push({ name: '应用及模块接入', params: { isRefresh: true }})
    },
    isNull(val) {
      if (!val) {
        this.disabled = false
        if (!this.rules.businessSystem) {
          this.rules.businessSystem = [
            { required: true, message: '请选择业务体系', trigger: 'change' }
          ]
        }
      } else {
        this.disabled = true
        if (this.rules.businessSystem) { delete this.rules.businessSystem }
        this.Form.businessSystem = ''
        // this.Form.businessSystem = 0
      }
    },
    validate(val, flag) {
      if (flag && val) {
        if (val === this.Form.appSetId) {
          this.$message.error('不能接入应用集本身')
          this.Form.appId = ''
        }
      } else if (!flag && val) {
        if (val === this.Form.appId) {
          this.$message.error('不能接入应用集本身')
          this.Form.appSetId = ''
        }
      }
    },
    selectChange(val) {
      this.validate(val, 0)
      const params = {
        appSetId: val
      }
      getBusinessSystem(params).then(res => {
        this.BusinessSystemList = res.data.data
      })
    },
    selectChange1(val) {
      this.validate(val, 1)
    },
    typeJudge(file) {
      const typeArry = ['.jpg', '.png', '.bmp', '.JPG', '.PNG', '.BMP', '.svg', '.SVG']
      const type = file.name.substring(file.name.lastIndexOf('.'))
      const isImage = typeArry.indexOf(type) > -1
      if (!isImage) {
        this.$message.warning('图片支持jpg、bmp、png、svg格式')
      }
      return isImage
    },
    success(res, file) {
      this.originalImg = res.data || ''
      this.visible = true
    },
    handleCroppedConfirm(res) {
      this.Form.icon = res.data
    },
    handleUploadChange(file) {
      const blob = new Blob([file.raw]) // 返回的文件流数据
      const path = window.URL.createObjectURL(blob)
      this.cropped = {
        url: path, // 转化为路径
        name: file.raw.name,
        type: file.raw.type
      }
      this.visible = true
    }
  }
}
</script>

<style lang="scss" scoped>
.formClass{
  margin-top: 10px;
}
.formContent{
  border-radius: 5px;
  border: 1px solid gray;
  padding: 15px;
}
.up{
  display: flex;
  width: 100%;
  margin-right: 50px;
  .right{
    width: 370px;
  }
  .left{
    width: calc(100% - 450px);
  }
}

.btn-group{
  margin-top: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar-uploader {
    border: 1px solid #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
  }
  .avatar-uploader:hover{
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 270px;
    height: 80px;
    line-height: 80px;
    text-align: center;
  }
  .el-upload__tip{
    text-align: center;
    line-height: 16px;
    padding-bottom: 10px;
  }
  .inputClass{
    width: calc(100% - 100px);
  }
  .bg-green{
    background-color: #3ec504;
  }
  .bg-red{
    background-color: #FF2F2F;
  }
</style>

<style lang="scss">
.apps{
  .el-select{
    width: calc(100% - 100px);
  }
  .flexbox{
    display: flex;
    height: 70px;
    align-items: center;
    justify-content: flex-start;
    img{
      width: 70px;
      height: 70px;
    }
    .flex{
      display: flex;
      height: 70px;
      flex-direction: column;
      justify-content:space-between;
      margin-left: 10px;
    }
    h3{
      margin: 0;
    }
    span{
      border-radius: 3px;
      width: 60px;
      text-align: center;
      color: #fff;
      font-size: 12px;
      padding: 5px 0;
    }
  }
}
</style>
